<?php
use Base\AdminController;
use JetBrains\PhpStorm\NoReturn;
use Traits\DataTree;

class CategoryController extends AdminController
{
    use DataTree;
    protected string $table = 'categories';

    protected string $model = "category";

    /**
     * 获取所有分类
     * @return void
     */
    #[NoReturn] public function getOptionsAction(): void
    {
        $data = CategoryModel::query()
            ->selectRaw("id,title as label,pid")
            ->get()
            ->toArray();
        $data = $this->getTree($data);
        $this->apiSuccess($data,"获取成功",20000);
    }

	    /**
     * 获取列表页数据
     * @return void
     */
    #[NoReturn] public function indexAction(): void
    {
        try {
            $sort = Request::input("sort");
            $orderBy = match ($sort)
            {
                "-id"=>'asc',
                default => 'desc',
            };
            if (Request::input("is_hid") !== null) {
                $this->where[] = ['is_hid','=',Request::input("is_hid")];
            }
			if (Request::input("title") !== null) {
                $this->where[] = ['title','like',"%".Request::input("title")."%"];
            }
            $sql = App::make($this->getModelMame())
                ->when($this->includes,function ($query,$value) {
                    $query->with($value);
                })->where($this->where)
                ->when($this->whereIn,function ($query,$value){
                foreach ($value as $item) {
                    $query->whereIn($item[0], $item[1]);
                }
            });
            if (Request::input("time")) {
                if (is_array(Request::input("time"))) {
                    $sql->whereBetween("created_at",Request::input("time"));
                }else {
                    $sql->whereDate("created_at",Request::input("time"));
                }
            }
            $data = $sql->orderBy("id",$orderBy)->paginate(Request::input("limit",10),['*'],NULL,Request::input("p",1));
            $result = [
                'items' =>  $this->getTree(collect($data->items())->toArray()),
                'total'=>$data->total(),
                'per_page' => $data->perPage(),
                'page' => $data->currentPage()
            ];
            $this->apiSuccess($result,"获取成功",20000);
        }catch (Exception $exception) {
            Log::$customFileName = LOG_PATH."/errors/";
            Log::error($exception->getMessage().$exception->getTraceAsString());
            $this->apiError($exception->getMessage());
        }
    }

}
